<template>
	<view class="cont_bo">
		<mtitles bgColor="none"></mtitles>
		<!-- <view class="cir_top_r"></view>
			<view class="cir_top_l"></view>
		<view class="cir_top_rs"></view> -->
		<view class="cont_conts">
			<view class="text-xll padding-left-xl text-c6">
				欢迎登录
			</view>
			<view class="padding-top-xl padding-lr-xl">
				<image class="img" :src="env.FileUrl+'food/ico/images/login_top01.png'" mode="aspectFit"></image>
			</view>
			<!-- <text class="fcon-logo login_icon"></text>
			<view class="login_text">炖大侠</view> -->
		</view>
		<view class="cont_bottoms">
			<block v-if="hasReg">
				<!-- @touchstart="handleTouchStart" -->
				<button v-if="canIUseGetUser&&0" class="submitBtn button" @click="tapLogin()" open-type="getUserInfo"  withCredentials="true" lang="zh_CN">
					登录
				</button>
				<button v-else class="submitBtn button" open-type="getUserInfo" @getuserinfo="tapOldLogin" withCredentials="true" lang="zh_CN">
					登录
				</button>
			</block>
			
			<button v-else class="submitBtn" open-type="getPhoneNumber"
				@getphonenumber="tapGetPhone" withCredentials="true" lang="zh_CN">
				<view>
					<text class="margin-left-xs">首次登录</text>
				</view>
			</button>
			<view class="protocol text-sm flex align-center">
				<view @click="isAgree=!isAgree">
					<text :class="[isAgree?'cuIcon-squarecheck':'cuIcon-square']" class="d_ib" style="font-size: 28rpx;"></text>
					<text class="padding-left-xs text-c9 d_ib padding-tb-sm">我已阅读并同意</text>
				</view>
				
				<text style="color:#5FC281;margin-left: 5rpx;" class="d_ib padding-tb-sm" @click="lookProtocol">《颐而康用户隐私协议》</text>
			</view>
		</view>
		<uni-popup ref="pop1" type="center">
			<view class="agrContent flex flex-direction padding-top-xl bg-white">
				<view class="flex-sub padding-lr-xl">
					<view class="text-xl text-c0 text-center">
						阅读并同意以下协议
					</view>
					<view class="padding-top textnc9 text-left">
						为了更好的保障您的合法权益，使用登录功能需要先阅读并同意<text class="text-ngreen"
							@click.stop="lookProtocol">《颐而康用户服务条款》</text>。
					</view>
				</view>
				<view class="mbot_btn solid-top flex margin-top-lg align-center text-xl text-center">
					<view class="flex-sub solid-right" @click.stop="tapHideModal">
						不同意
					</view>
					
					<button  v-if="canIUseGetUser" class="agrbtn full text-ngreen text-bold flex-sub"
						@click.stop="tapLogin('model')" withCredentials="true" lang="zh_CN">
						同 意
					</button>
					<button v-else class="submitBtn button" open-type="getUserInfo" @getuserinfo="tapOldLogin($event,'model')" withCredentials="true" lang="zh_CN">
						登录
					</button>
				</view>
			</view>
		</uni-popup>
		<loading></loading>
	</view>
</template>

<script setup lang="ts">
	import { onLoad,onShow,onUnload } from '@dcloudio/uni-app';
	import { showLoading, hideLoading } from '@/utils/helper';
	import {getWxPhone,getWxCodeLogin,regMemberAct} from '@/api/vmeitime-http/index.js';
	import {takeUserInfo} from '@/utils/public';
	
	import { env } from '@/api/env.js';
	import global from '@/utils/global';
	import mapi from '@/utils/mapi';
	import { ref } from 'vue';
	import { useUserStore } from '@/stores/commonStore';
	const userStore = useUserStore();
	const pop1 = ref(null)//协议弹窗
	const isAgree = ref(false)//协议
	const canTapLogin = ref(true)//能否点击
	const hasReg = ref(true)//是否注册
	const newCode = ref('')
	const evidence = ref({newCode:'',time:0,msgCode:''})//注册凭证
	const canIUseGetUser = ref(true)
	onLoad(()=>{
		canIUseGetUser.value = uni.getUserProfile?true:false;
		hideLoading();
	})
	onShow(()=>{
		if(evidence.value.newCode&&(evidence.value.time - (new Date().getTime())<=0)){
			hasReg.value = true
			changeStatu()
		}
	})
	onUnload(()=>{
		hideLoading();
		global.CENTER_LOGIN_PAGE = false; 
	})
	const lookProtocol = () => {
		uni.navigateTo({ url: '/pages/user/userProtocol/userProtocol' })
	}
	const scrKey = ref<any>({})
	// 点击登录-old	
	const tapOldLogin = async (info:any,source : string = '') => {
		console.log('taploginold',info);
		if (!isAgree.value && source != 'model') {
			showPop('pop1')
			changeStatu()
			return;
		}
		if (source == 'model') {
			isAgree.value = true
			hidePop('pop1')
		}
		if (!canTapLogin.value) { return; }
		showLoading()
		changeStatu(false)
		scrKey.value = info.detail||{};
		wxLogin()
	}
	// 点击登录-new
	const tapLogin = async (source : string = '') => {
		console.log('taplogin');
		if (!isAgree.value && source != 'model') {
			showPop('pop1')
			changeStatu()
			return;
		}
		if (source == 'model') {
			isAgree.value = true
			hidePop('pop1')
		}
		if (!canTapLogin.value) { return; }
		showLoading()
		changeStatu(false)
		scrKey.value = await getUserProfile()||{};
		wxLogin()
	}
	const tapHideModal = ()=>{
		changeStatu()
		hidePop('pop1')
	}
	const changeStatu = (v:any=true)=>{
		canTapLogin.value = v||true;
		v==true?hideLoading():''
	}
	const getUserProfile = ()=>{
		return new Promise((resolve, reject) => {
			uni.getUserProfile({
				desc: "获取你的昵称、头像、地区及性别",
				success: res => {
					console.log('getCode001', res)
					// const code = res.code;
					resolve(res);
				},
				fail: err => {
					mapi.msg(err||'网络繁忙，请稍后再试。')
					reject('')
					canTapLogin.value = true
					console.log('wx.login-err', err)
				}
			});
		});
	}
	//微信登录-s
	const wxLogin = async () => {
		let wxCode = await getCode()
		try {
			const {iv,encryptedData} = scrKey.value
			let res = await getWxCodeLogin({fromSystemId:'S039',fromAppId:'11',code:wxCode,iv:iv||'',encryptedData:encryptedData||''})
			if(!res.object||!res.result){
				mapi.msg('网络繁忙，请稍后再试.')
				clearnCache()
				changeStatu()
				return
			}
			//注册
			if(res.msgCode=='-103'){
				// newCode.value = res.object
				evidence.value = {
					newCode:res.object,
					msgCode:res.msgCode,
					time:(new Date().getTime()+4*60*1000),
				}
				clearnCache()
				changeStatu()
				hasReg.value = false
				return
			}
			// 登录
			if(res.result&&res.object){
				mapi.msg(res.shortMessage||'登录成功！')
				setLoginCache(res.object,true)
			}
			console.log('getWxCodeLogin', res)
		
		} catch (e) {
			changeStatu()
		}
	}
	//缓存用户信息
	// const getMemberInfo = async()=>{
	// 	try {
	// 		// showLoading()
	// 		let res = await queryMemberInfo()
	// 		hideLoading();
	// 		console.log('用户信息', res)
	// 		let nres = res.object||{};
	// 		if (res.result) {
	// 			userStore.setUserInfo(nres)
	// 		}
	// 	} catch (e) {
	// 		console.error('用户信息', e)
	// 		hideLoading();
	// 		mapi.msg('网络繁忙，请稍后再试!');
	// 	}
	// }
	//获取手机号
	const tapGetPhone = async (e : any) => {
		console.log('tapphone', e);
		if (!isAgree.value) {
			mapi.msg('请先同意"用户服务条款"再操作哦')
			return
		}
		let info = e.detail||{};
		if(!info.code){
			mapi.msg(info.errMsg||'网络繁忙，请稍后重试！')
			return
		}
		if (!canTapLogin.value) { return; }
		showLoading()
		try{
			let res = await getWxPhone({code:info.code,fromAppId:'11'})
			console.log('getWxPhone',res);
			if(res.result&&res.object){
				
				if(!evidence.value.newCode||(evidence.value.time - (new Date().getTime())<=0)){
					hasReg.value = true
					changeStatu()
					return
				}
				let regInfo = await regMemberAct({newCode:evidence.value.newCode,fromAppId:'11',fromSystemId:'S039',phone:res.object})
				hideLoading()
				if(regInfo.result&&regInfo.object&&regInfo.msgCode=='200'){
					setLoginCache(regInfo.object,true);
					userStore.setSelectAdress({})
					userStore.setChangeAdress(true)
					mapi.msg(regInfo.shortMessage||'注册成功！');
				}else{
					mapi.msg(regInfo.shortMessage||'注册失败！')
					setTimeout(()=>{
						uni.navigateBack()
					},800)
				}
				
			}else{
				clearnCache()
				changeStatu()
				mapi.msg(res.shortMessage||'网络繁忙，请稍后重试！')
			}
		}catch(e){
			changeStatu()
			//TODO handle the exception
		}
		
		// 
		// getWxPhone({})
		// 	.then(res => {
		// 		console.log('获取门店列表', res);
		// 		if (!res.result) {
		// 			// this.$hideLoading();
		// 			uni.showToast({
		// 				mask: true,
		// 				title: '获取门店失败！', //超过7个字符显示不全
		// 				icon: 'none'
		// 			});
		// 			return;
		// 		}
				
		// 		// this.$hideLoading();
		// 	})
		// 	.catch(err => {
		// 		// that.$hideLoading();
		// 		uni.showToast({
		// 			mask: true,
		// 			title: '获取门店失败！', //超过7个字符显示不全
		// 			icon: 'none'
		// 		});
		// 		console.log('获取门店列表失败', err);
		// 	});
		
	}
	
	const setLoginCache = async(token:any,isLogin:boolean)=>{
		// uni.setStorageSync(this.$global.USER_INFO, cacheInfo);
		uni.setStorageSync(global.USER_TIKET, token);
		uni.setStorageSync(global.IS_LOGIN,isLogin);
		await takeUserInfo();
		setTimeout(()=>{
			uni.navigateBack()
		},300)
	}
	const clearnCache = ()=>{
		// uni.setStorageSync(this.$global.USER_INFO, '');
		uni.setStorageSync(global.USER_TIKET, '');
		uni.setStorageSync(global.IS_LOGIN,false);
	}
	// 微信登录-e
	let lastTouchEndTime = 0, lastTouchClientX = 0, lastTouchClientY = 0

	const handleTouchStart = (event)=>{
		const { clientX, clientY } = event.touches[0];
		const currentTime = Date.now();

		if (currentTime - lastTouchEndTime < 3000 && // 300ms内再次点击
			Math.abs(clientX - lastTouchClientX) < 30 && // 30px内的位置偏移
			Math.abs(clientY - lastTouchClientY) < 30) {
			// 触发双击事件
			onDoubleClick();
		}

		// 更新上一次点击的时间和位置
		lastTouchEndTime = currentTime;
		lastTouchClientX = clientX;
		lastTouchClientY = clientY;
	}

	const onDoubleClick = () => {
		console.log('双击事件触发');
		// 双击事件的处理逻辑
	}


	// const doubleClickHandler = {
	// 	lastTouchEndTime: 0,
	// 	lastTouchClientX: 0,
	// 	lastTouchClientY: 0,

	// 	handleTouchStart(event) {
	// 		const { clientX, clientY } = event.touches[0];
	// 		const currentTime = Date.now();

	// 		if (currentTime - this.lastTouchEndTime < 300 && // 300ms内再次点击
	// 			Math.abs(clientX - this.lastTouchClientX) < 30 && // 30px内的位置偏移
	// 			Math.abs(clientY - this.lastTouchClientY) < 30) {
	// 			// 触发双击事件
	// 			this.onDoubleClick();
	// 		}

	// 		// 更新上一次点击的时间和位置
	// 		this.lastTouchEndTime = currentTime;
	// 		this.lastTouchClientX = clientX;
	// 		this.lastTouchClientY = clientY;
	// 	},

	// 	onDoubleClick() {
	// 		console.log('双击事件触发');
	// 		// 双击事件的处理逻辑
	// 	}
	// };
	const getCode = () => {
		return new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: res => {
					console.log('getCode001', res)
					const code = res.code;
					resolve(code);
				},
				fail: err => {
					reject('')
					canTapLogin.value = true
					console.log('wx.login-err', err)
				}
			});
		});
	}
	const showPop = (source : string = '') => {
		switch (source) {
			case 'pop1':
				pop1.value?.open()
				break;
			default:
				break;
		}
	}
	const hidePop = (source : string) => {
		switch (source) {
			case 'pop1':
				pop1.value?.close()
				break;
			default:
				break;
		}
	}
</script>

<style lang="scss" scoped>
	.cont_bo {
		width: 100vw;
		height: 100vh;
		background-color: #FDFFFF;
		position: relative;
		overflow: hidden;
		background-image: url("https://cdn-static.yekjx.com/food/logo/images/log_bg.png");
		background-size: 100% 100%;
		background-repeat: no-repeat;

		// .cir_top_r {
		// 	width: 404rpx;
		// 	height:434rpx;
		// 	background-image: linear-gradient(180deg, #FAFDFE 0%, #EBF6FF 49%, #EDFFE7 100%);
		// 	filter: blur(32rpx);
		// 	position: absolute;
		// 	top:0;
		// 	right:0;
		// 	z-index: 1;
		// 	border-radius: 50%;
		// }
		//  .cir_top_l{
		//  width: 576rpx;
		//  height:576rpx;
		//  border-radius: 50%;
		//  background-image: linear-gradient(180deg, #FAFDFE 0, #AAD9FF 49%, #29E068 120%);
		//  filter: blur(32rpx);
		//  position: absolute;
		//  left:-260rpx;
		//  top: 400rpx;
		//  z-index: 1;
		// }
		// .cir_top_rs{
		//  width: 694rpx;
		//  height:694rpx;
		//  border-radius: 50%;
		//  background-image: linear-gradient(145deg, #EDF8FD -1.02%, rgba(41, 224, 104, 0.50) 101.99%);
		//  // filter: blur(208rpx);
		//  position: absolute;
		//  right:-320rpx;
		//  bottom: -20rpx;
		//  z-index: 1;
		// }
		.cont_conts {
			width: 100%;
			height: 260rpx;
			z-index: 99;
			position: absolute;
			top: 260rpx;
			left: 0rpx;

			.login_icon {
				color: #53A87F;
				font-size: 140rpx;
				margin-left: 302rpx;
			}

			.login_text {
				color: #53A87F;
				font-family: "Microsoft YaHei UI";
				font-size: 64rpx;
				font-weight: 400;
				margin: 30rpx 0rpx 0rpx 270rpx;
			}
			.img{
				width: 100%;
				height: 116rpx;
			}
		}

		.cont_bottoms {
			width: 100%;
			height: 164rpx;
			position: absolute;
			top: 870rpx;
			left: 0rpx;
			padding: 0rpx 20rpx 0rpx 20rpx;

			.submitBtn {
				width: 100%;
				height: 104rpx;
				border-radius: 4rpx;
				background: #6AC689;
				text-align: center;
				line-height: 104rpx;
				color: #FFF;
				font-family: ABeeZee;
				font-size: 32rpx;
				font-weight: 400;
				letter-spacing: 0.4rpx;
			}

			// .protocol {
			// 	margin-top: 20rpx;
			// 	font-size: 24rpx;
			// }
		}
	}

	.agrContent {
		width: 622rpx;
		min-height: 380rpx;
		border-radius: 24rpx;
	}

	.textnc9 {
		color: #969799;
		line-height: 1.4;
	}

	.mbot_btn,
	.mbnitm {
		height: 96rpx;
		line-height: 97rpx;
	}

	.agrbtn {
		margin: 0;
		padding: 0;

		&::after {
			border: none;
		}
	}
</style>